const{
    callContainerApi
} = require("../../utils/util")
Page({
    data: {
        categories: [],
        originalCategories: [],
        searchKey: "",
        loading: true,
        Merchantid: null,
        showAllButton: false,
        expandedStates: {} // 保存所有分类的展开状态11
    },

    onLoad(options) {
        try {
            const userInfo = JSON.parse(decodeURIComponent(options.userInfo));
            this.setData({
                Merchantid: userInfo     // 使用解析的用户信息或默认值
            });
        } catch (e) {
            console.error('解析用户信息失败:', e);
            wx.showToast({
                title: '获取用户信息失败',
                icon: 'none'
            });
            return;
        }
        this.loadGoodsList(this.data.Merchantid);
    },

    // 页面显示时检查是否需要刷新
    onShow() {
        const needRefresh = wx.getStorageSync('needRefreshGoodsList');
        if (needRefresh) {
            // 保存当前展开状态
            this.saveExpandedStates();
            this.loadGoodsList(this.data.Merchantid);
            wx.removeStorageSync('needRefreshGoodsList');
        }
    },

    async loadGoodsList(merchantId) {
        this.setData({ loading: true });
        
        try {
            // 保存当前展开状态（在加载新数据前）
            const currentExpandedStates = this.data.expandedStates;
            
            // 尝试获取完整的商品树结构
            await callContainerApi(`/product/tree?merchantId=${merchantId}`,"GET",null)
            .then(res=>{
                console.log(res)
                this.setData({
                        categories: res.data.data.childs
                })
            })

            let newCategories = [];
            
            const {
                    categories
            } = this.data

            newCategories = categories.map(category => {
                const validChilds = (category.childs || []).filter(child => child !== null && child !== undefined);
                const newSubCategories = validChilds.map(subCategory => {
                    const validGoods = (subCategory.childs || []).filter(good => good !== null && good !== undefined);
                    const newGoods = validGoods.map(item => {
                        const spec = item.specifications && item.specifications[0] || {};
                        const specifications = item.specifications || [];
                        return {
                            id: item.id,
                            name: item.name,
                            desc: item.desc || '',
                            image: item.wxFileId || '',
                            price: spec.price || 0,
                            spec: spec.spec || '份',
                            specId: spec.specId,
                            pictures: item.pictures || [],
                            specList: specifications,
                            // 确保每个商品都使用当前二级分类的ID
                            subCategoryId: subCategory.id
                        };
                    });
                    
                    // 打印检查：确保同一二级分类下的商品ID一致
                    // console.log(`二级分类 ${subCategory.name} (ID: ${subCategory.id}) 下的商品数量: ${newGoods.length}`);
                    // newGoods.forEach(good => {
                    //     console.log(`  商品 ${good.name} 的 subCategoryId: ${good.subCategoryId}`);
                    // });
                    
                    return {
                        ...subCategory,
                        childs: newGoods,
                        expanded: false
                    };
                });
                
                return {
                    ...category,
                    childs: newSubCategories,
                    expanded: false
                };
            });

            
            // 恢复之前的展开状态
            
            const restoredCategories = this.restoreExpandedStates(newCategories, currentExpandedStates);
            
            // 更新页面数据
            this.setData({
                categories: restoredCategories,
                originalCategories: restoredCategories,
                loading: false
            });
            
            // 存储商品数据到本地
            wx.setStorageSync('categories', restoredCategories);
            
        } catch (error) {
            console.error('加载数据失败:', error);
            wx.showToast({
                title: '加载数据失败',
                icon: 'none'
            });
        } finally {
            this.setData({ loading: false });
        }
    },

    // 恢复分类展开状态（改进版）
    restoreExpandedStates(categories, expandedStates = {}) {
        if (!categories || categories.length === 0) return categories;
        
        return categories.map((category, categoryIndex) => {
            // 确保分类有id，否则生成临时id
            const categoryId = category.id || `temp_${categoryIndex}`;
            // 检查一级分类的展开状态
            const categoryKey = `category_${categoryId}`;
            if (expandedStates[categoryKey] !== undefined) {
                category.expanded = expandedStates[categoryKey];
            } else {
                category.expanded = false; // 默认为折叠状态
            }
            
            // 处理子分类
            if (category.childs && category.childs.length > 0) {
                category.childs = category.childs.map((subCategory, subCategoryIndex) => {
                    // 确保子分类有id，否则生成临时id
                    const subCategoryId = subCategory.id || `temp_${categoryIndex}_${subCategoryIndex}`;
                    const subCategoryKey = `subCategory_${subCategoryId}`;
                    
                    if (expandedStates[subCategoryKey] !== undefined) {
                        subCategory.expanded = expandedStates[subCategoryKey];
                    } else {
                        subCategory.expanded = false; // 默认为折叠状态
                    }
                    
                    return subCategory;
                });
            } else {
                category.childs = []; // 确保childs存在
            }
            
            return category;
        });
    },

    // 保存分类展开状态（改进版）
    saveExpandedStates() {
        const { categories } = this.data;
        const expandedStates = {};
        
        if (!categories || categories.length === 0) {
            this.setData({ expandedStates });
            return;
        }
        
        categories.forEach((category, categoryIndex) => {
            // 确保分类有id，否则使用临时id
            const categoryId = category.id || `temp_${categoryIndex}`;
            // 保存一级分类的展开状态
            expandedStates[`category_${categoryId}`] = category.expanded;
            
            // 处理子分类
            if (category.childs && category.childs.length > 0) {
                category.childs.forEach((subCategory, subCategoryIndex) => {
                    // 确保子分类有id，否则使用临时id
                    const subCategoryId = subCategory.id || `temp_${categoryIndex}_${subCategoryIndex}`;
                    expandedStates[`subCategory_${subCategoryId}`] = subCategory.expanded;
                });
            }
        });
        
        this.setData({
            expandedStates
        });
    },

    toggleCategory(e) {
        const index = e.currentTarget.dataset.index;
        const categories = this.data.categories;
        
        if (index >= 0 && index < categories.length) {
            categories[index].expanded = !categories[index].expanded;
            this.setData({
                categories
            });
            
            // 保存展开状态
            this.saveExpandedStates();
        }
    },

    toggleSubCategory(e) {
        const categoryIndex = e.currentTarget.dataset.categoryIndex;
        const subCategoryIndex = e.currentTarget.dataset.subCategoryIndex;
        const categories = this.data.categories;
        
        if (categoryIndex >= 0 && categoryIndex < categories.length && 
            categories[categoryIndex].childs && 
            subCategoryIndex >= 0 && subCategoryIndex < categories[categoryIndex].childs.length) {
            
            categories[categoryIndex].childs[subCategoryIndex].expanded = 
                !categories[categoryIndex].childs[subCategoryIndex].expanded;
            
            this.setData({
                categories
            });
            
            // 保存展开状态
            this.saveExpandedStates();
        }
    },


    onSearchInput(e) {
        this.setData({
            searchKey: e.detail.value
        });
    },

    onSearch() {
        const { searchKey, originalCategories } = this.data;
        if (searchKey) {
            const newCategories = originalCategories.map(category => {
                const newSubCategories = category.childs.map(subCategory => {
                    const newGoods = subCategory.childs.filter(item => item.name.includes(searchKey));
                    return {
                        ...subCategory,
                        childs: newGoods
                    };
                }).filter(subCategory => subCategory.childs.length > 0);
                return {
                    ...category,
                    childs: newSubCategories
                };
            }).filter(category => category.childs.length > 0);
            this.setData({
                categories: newCategories,
                showAllButton: true
            });
        } else {
            this.setData({
                categories: this.data.originalCategories,
                showAllButton: false
            });
        }
    },

    showAllGoods() {
        this.setData({
            categories: this.data.originalCategories,
            searchKey: "",
            showAllButton: false
        });
    },

    editGoods(e) {
        const item = e.currentTarget.dataset.item;
        const categoryIndex = e.currentTarget.dataset.categoryIndex;
        const subCategoryIndex = e.currentTarget.dataset.subCategoryIndex;
        const category = this.data.categories[categoryIndex];
        const subCategory = category.childs[subCategoryIndex];
        
        // 验证商品的subCategoryId与当前子分类ID是否一致
        // console.log(`编辑商品 ${item.name}: 商品subCategoryId=${item.subCategoryId}, 当前子分类ID=${subCategory.id}`);
        
        // 把item对象转换为JSON字符串，再进行URL编码
        const encodedItem = encodeURIComponent(JSON.stringify(item));
        wx.navigateTo({
            url: `/pages/M_goods_edit/M_goods_edit?item=${encodedItem}&userInfo=${encodeURIComponent(JSON.stringify(this.data.Merchantid))}&subCategoryId=${item.subCategoryId}`
        });
    },

    deleteGoods(e) {
        const id = e.currentTarget.dataset.id;
        wx.showModal({
            title: '提示',
            content: '确定要删除该商品吗？',
            success: (res) => {
                if (res.confirm) {
                    // 保存当前展开状态
                    this.saveExpandedStates();
                    callContainerApi("/product/merchandise?merchandiseId=" + id,"DELETE",null)
                    .then(res => {
                        wx.showToast({
                            title: '删除成功',
                            icon: 'success',
                            duration: 2000
                        });
                            // 刷新商品列表  
                        this.loadGoodsList(this.data.Merchantid);

                    }).catch(error => {
                        console.error('删除商品失败:', error);
                        wx.showToast({
                            title: '删除失败，请重试',
                            icon: 'none'
                        });
                    });
                }
            }
        });
    },

    // 添加一级分类
    addCategory() {
        wx.showModal({
            title: '添加一级分类',
            editable: true,
            placeholderText: '请输入分类名称',
            success: (res) => {
                if(!res.confirm){
                    return
                }
                if(!res.content.trim()){
                    wx.showToast({
                        title: '分类名称不能为空',
                        icon: 'none'
                    })
                }
                const postName = encodeURI(res.content.trim())

                // 保存当前展开状态
                this.saveExpandedStates();
                    
                callContainerApi(`/product/category?categoryName=${postName}`,"POST",null)
                 .then(res1 => {
                    wx.showToast({
                        title: '添加成功',
                        icon: 'success'
                    });
                    // 刷新商品列表
                    this.loadGoodsList(this.data.Merchantid)
                }).catch(error => {
                    console.error('添加分类失败:', error);
                    wx.showToast({
                        title: '添加失败，请重试',
                        icon: 'none'
                    });
                }); 
            }
        });
    },

    // 添加二级分类
    addSubCategory(e) {
        const index = e.currentTarget.dataset.index;
        wx.showModal({
            title: '添加二级分类',
            editable: true,
            placeholderText: '请输入分类名称',
            success: (res) => {
                if (res.confirm && res.content.trim()) {
                    const categories = this.data.categories;
                    const postName = encodeURI(res.content.trim())

                    
                    // 保存当前展开状态
                    this.saveExpandedStates();
                    
                    callContainerApi(`/product/category?categoryName=${postName}&&parentId=${categories[index].id}`,"POST")
                    .then(res1 => {
                        if (res1.data.code === 200) {
                            wx.showToast({
                            title: '添加成功',
                            icon: 'success'
                            });
                            // 刷新商品列表
                            this.loadGoodsList(this.data.Merchantid);
                        } else {
                            wx.showToast({
                            title: '添加失败，请重试',
                            icon: 'none'
                            });
                        }
                    }).catch(error => {
                        console.error('添加分类失败:', error);
                        wx.showToast({
                            title: '添加失败，请重试',
                            icon: 'none'
                        });
                    });
                } else if (res.confirm) {
                    wx.showToast({
                        title: '分类名称不能为空',
                        icon: 'none'
                    });
                }
            }
        });
    },

    // 删除一级分类
    deleteCategory(e) {
        const index = e.currentTarget.dataset.index;
        wx.showModal({
            title: '提示',
            content: '确定要删除该一级分类吗？',
            success: (res) => {
                if (res.confirm) {
                    const categories = this.data.categories;
                    
                    // 保存当前展开状态
                    this.saveExpandedStates();
                    callContainerApi(`/product/category?categoryId=${categories[index].id}`,"DELETE",null)
                    .then(res1 => {
                        if (res1.data.status === 200) {
                            wx.showToast({
                            title: '删除主类成功',
                            icon: 'success'
                            });
                            // 刷新商品列表
                            this.loadGoodsList(this.data.Merchantid);
                        } else {
                            wx.showToast({
                            title: '删除主类失败，请重试',
                            icon: 'none'
                            });
                        }
                    }).catch(error => {
                        console.error('删除分类失败:', error);
                        wx.showToast({
                            title: '删除失败，请重试',
                            icon: 'none'
                        });
                    });
                }
            }
        });
    },

    // 删除二级分类
    deleteSubCategory(e) {
        const categoryId = e.currentTarget.dataset.categoryId;
        wx.showModal({
            title: '提示',
            content: '确定要删除该二级分类吗？',
            success: (res) => {
                if (res.confirm) {
                    
                    // 保存当前展开状态
                    this.saveExpandedStates();
                    
                    callContainerApi(`/product/category?categoryId=${categoryId}`,"DELETE",null)
                    .then(res1 => {
                        console.log(res1)
                        if (res1.data.status === 200) {
                            wx.showToast({
                            title: '删除子类成功',
                            icon: 'success'
                            });
                            // 刷新商品列表
                            this.loadGoodsList(this.data.Merchantid);
                        } else {
                            wx.showToast({
                            title: '删除子类失败，请重试',
                            icon: 'none'
                            });
                        }
                    }).catch(error => {
                        console.error('删除分类失败:', error);
                        wx.showToast({
                            title: '删除失败，请重试',
                            icon: 'none'
                        });
                    });
                }
            }
        });
    },

    // 添加商品到二级分类
    addGoodsToSubCategory(e) {
        const item = e.currentTarget.dataset.item;
        const categoryIndex = e.currentTarget.dataset.categoryIndex;
        const subCategoryIndex = e.currentTarget.dataset.subCategoryIndex;
        const category = this.data.categories[categoryIndex];
        const subCategory = category.childs[subCategoryIndex];
        wx.navigateTo({
            url: `/pages/M_goods_edit/M_goods_edit?userInfo=${encodeURIComponent(JSON.stringify(this.data.Merchantid))}&subCategoryId=${subCategory.id}`
        });
    }
});